﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommModule.Connection;
using CommModule.Messages;

namespace CERTCOP_C
{
    public class CertcopConnectionThread
    {
        private TCPSecureSocket _tcpSocket;

        private Dictionary<int, Session> _sessionHandlers;

        private bool _isRunning;

        private List<Object> _messagesToSend;

        public bool IsRunning
        {
            set { _isRunning = value; }
        }

        public CertcopConnectionThread()
        {
            _tcpSocket = new TCPSecureSocket();
            _sessionHandlers = new Dictionary<int, Session>();
            _messagesToSend = new List<object>();
            _isRunning = true;
        }

        public void Run()
        {
            while (_isRunning && _tcpSocket.IsSecureChannelEstablished())
            {
                //Process client requests in certcop
                //Manage sessions
            }
        }

        public void sendCertcopRequest(int sessionId, Object obj)
        {
            Session sessionHandler;

            if (_sessionHandlers.ContainsKey(sessionId))
                sessionHandler = _sessionHandlers[sessionId];
            else
            {
                sessionHandler = new Session(sessionId);
                _sessionHandlers.Add(sessionId, sessionHandler);
            }

            _tcpSocket.Send(obj);
        }

        public Object receiveCertcopAnswer(int sessionId)
        {
            if (_sessionHandlers.ContainsKey(sessionId))
            {
                Session sessionHandler = _sessionHandlers[sessionId];
                return sessionHandler.getSessionMessage();
            }

            return null;
        }
    }
}
